package com.sh.线程安全相关.lock锁;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description:
 */
public class MyThread extends Thread {
    static int tickets = 0;

    static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            while (true) {
                lock.lock();
                try {
                    if (tickets < 100) {
                        tickets++;
                        System.out.println(Thread.currentThread().getName() + "正在卖" + tickets);
                        Thread.sleep(10L);
                    } else {
                        break;
                    }
                } catch (RuntimeException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}

